package org.zezs.sync.mongo.config.sync;

import com.alibaba.fastjson.JSONArray;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zezs.sync.mongo.Constants;
import org.zezs.sync.mongo.config.sync.metadata.SyncEnt;
import org.zezs.sync.mongo.dataProess.DefaultJsProesser;
import org.zezs.sync.mongo.dataProess.Proesser;
import org.zezs.sync.mongo.utils.InputStreamUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class SyncUtil {

    static Logger logger = LoggerFactory.getLogger(DefaultJsProesser.class);

    public static List<SyncEnt> init() {
        try {
//            byte[] copyToByteArray = FileCopyUtils.copyToByteArray(resourceAsStream);
            byte[] copyToByteArray = InputStreamUtil.readAll(Constants.syncfile);
            List<SyncEnt> parse = JSONArray.parseArray(new String(copyToByteArray, "utf-8"), SyncEnt.class);
            parse.forEach(syncEnt -> {
                syncEnt.getChains().forEach(chains -> {
                    if(StringUtils.isNotBlank(chains.getJavaProesser())){
                        try{
                            Class<?> aClass = Class.forName(chains.getJavaProesser());
                            Object o = aClass.newInstance();
                            chains.setProesser((Proesser) o);
                        }catch (Exception e){
                            logger.error("脚本初始化失败 {}", chains.getJavaProesser());
                        }

                    }
                });
            });
            return parse;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ArrayList<>();
    }
}
